<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/3/9
 * Time: 14:14
 */

/**
 * @param $code
 * @param $message
 * @param null $info
 */
function json_exit ($code, $message, $info = NULL)
{
    $rt = array(
        'code' => $code,
        'msg' => $message
    );

    if ($info !== NULL)
    {
        $rt['info'] = $info;
    }

    echo json_encode($rt);
    exit();
}

/**
 * 自定义的错误处理函数
 * @param $errno
 * @param $errstr
 * @param $errfile
 * @param $errline
 */
function my_error_handler($errno, $errstr, $errfile, $errline)
{
    if ($errno === E_USER_ERROR)
    {
        list($errmsg, $errcode) = explode('|', $errstr, 2);
        if (!$errcode)
        {
            $errcode = 500;
        }
        json_exit($errcode, $errmsg);
    }
    else
    {
        _error_handler($errno, $errstr, $errfile, $errline);
    }
}

/**
 * 返回错误
 * @param $errcode
 * @param $errmsg
 */
function error($errcode, $errmsg)
{
    trigger_error("$errmsg|$errcode", E_USER_ERROR);
}

/**
 * 简单记录日志方便调试
 * @param $message
 */
function easyLog($message)
{
    $logFile = APPPATH. 'logs/easyLog_' . date('Y-m-d') . '.log';

    $message = '[' . date('Y-m-d H:i:s') . ']  ' . $message . PHP_EOL . PHP_EOL;

    file_put_contents($logFile, $message, FILE_APPEND);

    if (posix_getuid() === 0)
    {
        chown($logFile, 'nobody');
        chgrp($logFile, 'nobody');
    }
}




/**
 * curl封装方法
 * @param $url
 * @param $params
 * @param string $method
 * @param int $timeout
 * @return mixed
 */
function httpCurl($url, $params, $method='GET', $timeout = 10)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HEADER, 0);

    $params = http_build_query($params);

    if ($method == 'GET')
    {
        if (parse_url($url, PHP_URL_QUERY))
        {
            $url = rtrim($url, '&');
            $url .= '&' . $params;
        }
        else
        {
            $url = rtrim($url, '?');
            $url .= '?' . $params;
        }
    }

    curl_setopt($ch, CURLOPT_URL, $url);

    if ($method == 'POST')
    {
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }

    $res = curl_exec($ch);

    curl_close($ch);

    return $res;
}

/**
 * @param $params
 * 必填参数验证
 */
function mustParams($params)
{
    foreach($params as $key=>$value){
        if(empty($value)){
            json_exit(10004,'缺少参数');
        }
    }
}

  // 单位自动转换函数
    function getRealSize($size){
        $kb = 1024;         
        $mb = 1024 * $kb;   
        $gb = 1024 * $mb;   
        $tb = 1024 * $gb;  
         
        if($size < $kb)
        {
            return $size." B";
        }
        else if($size < $mb)
        {
            return round($size/$kb,2)." KB";
        }
        else if($size < $gb)
        {
            return round($size/$mb,2)." MB";
        }
        else if($size < $tb)
        {
            return round($size/$gb,2)." GB";
        }
        else
        {
            return round($size/$tb,2)." TB";
        }
    }

    /**
     * 获取扩展名
     */

    function getExt($str){

        $arr = explode('.', trim($str));
     
        return array_pop($arr);
    }
    /**
    *根据后缀名获取图片地址
    */
    function getImg($ext){
        switch ($ext) {
            case 'jpg':
               return  "/file_service/resource/img/mime_img32.png";
                break;
            case 'png':
                 return  "/file_service/resource/img/mime_img32.png";
                break;
            case 'zip':
                return  "/file_service/resource/img/mime_compress32.png";
                break;
                case 'txt':
                return  "/file_service/resource/img/mime_txt32.png";
                break;
				case 'gif':
                return  "/file_service/resource/img/mime_img32.png";
                break;
            default:
               return  "/file_service/resource/img/file.png";
                break;
        }
    }


    /**
    *@path文件存储路径
    *@newname文件新名称
    *@oldname文件旧名称
    */
    function fileRename($path,$newname,$oldname){
        $oldname = $path.$oldname;
        $newname = $path.$newname;
        if(!file_exists($oldname)||file_exists($newname)){
            json_exit('20003',"目标文件存在或源文件不存在");
        }else{
            $h =rename($oldname, $newname);
        }      
        if($h){
            return true;
        }else{
            return false;
        }
    }

/**
*带宽计算
*/
function changeWide($size) {
        $size *= 8;
        if($size > 1024 * 1024 * 1024) {
                $size = round($size / 1073741824 * 100) / 100 . ' Gbps';
        } elseif($size > 1024 * 1024) {
                $size = round($size / 1048576 * 100) / 100 . ' Mbps';
        } elseif($size > 1024) {
                $size = round($size / 1024 * 100) / 100 . ' Kbps';
        } else {
                $size = $size . ' Bbps';
        }
        return $size;
}

/**
*每天下载5分钟日志
*/
function dayLog($mercode,$downLoadtimes,$downLoadsize,$bandWide){
    $date = date("Ymd");
    $time = date('Y-m-d H:i:s');
    $logpath = '/data/log/file_service/'.$date.'/';
    if(!file_exists($logpath)){
        mkdir($logpath);
    }
    $log = $date."|".$mercode."|".$downLoadtimes."|".$downLoadsize."|".$bandWide."|". $time;
    file_put_contents($logpath.date("Y-m-d").'dayLoad.txt',$log. "\r\n",FILE_APPEND);
}
/**
*通用下载日志
*@$vid
*@mercode商户号
*$muid
*download下载文件名
*/
function commonLog($vid,$mercode,$muid,$download){
    $time = date('Y-m-d H:i:s');
    static $id;
    $date = date("Ymd");
    $logpath = '/data/log/file_service/'.$date.'/';
    if(!file_exists($logpath)){
        mkdir($logpath);
    }
    $id++;
    $log = $id."|".$mercode."|".$vid."|".$muid."|".$download."|".$time;
    file_put_contents($logpath.date("Y-m-d").'downLoad.txt',$log. "\r\n",FILE_APPEND);
}
/**
*5分钟带宽流量
*@$total下载总流量
*@$starttime开始下载时间
*@$endtime结束下载时间
*/
 function bandWide($total,$start,$end)
 {
    //$x当前时间
    //$s为开始时间
    //start/end下开始时间和结束时间   
    $t = $total;//总流量
    $x = getMicrotime();//当前时间
    $s = $start;
    $e = $end;  
    $r = round($t/($end-$start));//每秒下载流量
	//echo $r;die;
    $m = $s/300;//一天内每5分钟一片后的序号

    $s=$m*300;
    $m = round($m);
    while ( $s< $e) {
        if($s<=$x&&$s+300>=$e){			
            $d[$m]=$t;
            break;
        }else if($s<=$x){
            $d[$m]=(300+$s-$x)*$r;
        }else if($x>=$e){
            $d[$m]=(300+$e-$s)*$r;
        }else{
            $d[$m]=300*$r;
        }
        $m++;
        $x+=300;
    }
    return $d[$m];
 }
 /**
 *获取当前时间精确到毫秒
 */
 function getMicrotime(){

   list($usec, $sec) = explode(" ", microtime());
	
	$sec = ((float)$usec + (float)$sec);
   return round($sec,2);

}
/**
*dayLoad图表展示数据文件
*/
function dayJsonLog($datetime,$bandWide){

}

